import axios from 'axios'
import { MessageBox, Message ,Notification} from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent
    //在发送请求之前吧token放到请求头中
    if (store.getters.token) {
      //这里的token 要和后端保持一致
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    //如果出错弹出一个错误的日志
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // console.log(response)
    const res = response.data // response.data里面的数据才是后台返回给我们的数据  400  401  200  500
    if (res.code === 401) {
      // 身份过期
      MessageBox.confirm('用户登陆身份已过期，请重新登陆', '系统提示', {
        confirmButtonText: '重新登陆',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/logout').then(() => { // 跳到登陆页面重新登陆
          location.reload()
        })
      })
    } else if (res.code === 500) {
      Notification.error({
        title: res.msg
      })

      return Promise.reject("error")// 记录错
    } else if (res.code ==400) { // 可能是其它参数出错
      
      Notification.error({  
        title: res.msg
      })
      return Promise.reject("error")// 记录错
    } else {
      // 以上验证通过之后再放行
      return Promise.resolve(res)
    }
  },
  error => {
    // console.log('err' + error) // for debug
    return Promise.reject('err'+error)
  }
)


export default service
